import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
//通过 FileChannel 将 给定路径下文件读出到控制台
public class FileChannelDemo01 {
    private static final int MAX_SIZE = 1024;
    public static void main(String[] args) throws IOException {
        //1.创建文件
        RandomAccessFile accessFile = new RandomAccessFile("D:\\JavaLearn\\idea\\Code\\JavaSE_Code\\MyNet\\src\\tmp\\nio.txt", "rw");
        //2.创建通道
        FileChannel accessFileChannel = accessFile.getChannel();
        //3.创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(MAX_SIZE);
        int len ;
        while( (len = accessFileChannel.read(buffer) ) != -1){  //将文件内容读取到缓冲区
            byte[] bys = new byte[len];        //创建字节数组接收
            for(int i = 0; i < len; i++){
                bys[i] = buffer.get(i);        //将缓存区内容存到字节数组中
            }
            System.out.println(new String(bys,0,len));
            buffer.flip();                     //反转读写模式
        }
        buffer.clear();                        //清除缓存区内容

        accessFileChannel.close();
    }
}
